const App = {
  mixins: [Query], //配置文件，路径/utils/mixins.js
  data() {
    return {
      partyMemberMonthlyData: [],
      partyOrgMonthlyData: [],
      monthColors: [
        "#e85858",
        "#f09ab2",
        "#9fbf6a",
        "#6fbbc8",
        "#a79ecb",
        "#f7ac69",
        "#ea5859",
        "#f19ab2",
        "#9fbf6a",
        "#6fbbc7",
        "#a79ecb",
        "#f7ac69",
      ],
      statistics: {
        total: { completed: 0, total: 0 }, // 全部
        partyCongress: { completed: 0, total: 0 }, // 已交纳
        partyCommittee: { completed: 0, total: 0 }, // 未交纳
      },
      teeed: "",
      party_fees: {
        Party_Fee_SerialNumber: "", //党费缴纳流水号
        Party_Member_SerialNumber: "", //党员流水号
        Party_Organization_SerialNumber: "", //所属党组织编号
        Fee_Date: "", //党费日期
        Fee_Amount: "", //党费金额
      },
      totalMembers: 111, //总人数
      fullMembers: 11, //正式党员
      probationaryMembers: 1, //预备党员
      input: "", //输入框
      value2: getYMDate(),
      options: [
        //下拉菜单
        {
          value: "1",
          label: "已交纳",
        },
        {
          value: "0",
          label: "未交纳",
        },
      ],
      treeData: [], //树的数据
      total: [],
      originalTreeData: [], //原始树的数据
      originalTableData: [], // 原始表格的数据
      columns: [], //表格的列
      loading: false, //表数据的懒加载
      showDialog: false, //设置字段弹窗
      checkedFields: [], //选中的字段
      isDataReady: false,
      Tabletdata: [], //表格的数据
      fields: [], //字段列表
      // showaddDialog: false, //添加字段弹窗
      value: "",
      page: {
        PageNumber: 1, //页码
        RowAmount: 10,
        Condition: window.btoa(
          unescape(
            encodeURIComponent(getYMDate() + "," + getYMDate() + ",%%,%%")
          )
        ),
        ExtensionCondition: "",
        ExtensionCondition1: "",
      },
      calendar: false,
      Party_Organization_SerialNumber: "",
      organization: [],
      Fee_Date: "",
      showDialog2: false,
      Manager: [],
    };
  },
  mounted() {
    let a = getCookie("user"); // 获取cookie
    console.log(a);

    // $.ajax({
    //   headers: requestHeaders(),
    //   url: `${mh}/generalBusiness/generalQueryByTableName`,
    //   type: "POST",
    //   data: {
    //     Data: "party_organization",
    //     Condition: "Row_Status='0'",
    //   },
    //   success: (data) => {
    //     this.organization = data; // 直接使用 this
    //   },
    //   complete: (XMLHttpRequest) => {
    //     requestPretreatment(XMLHttpRequest);
    //   },
    //   dataType: "json",
    // });
    // $.ajax({
    //   headers: requestHeaders(),
    //   url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
    //   type: "POST",
    //   data: {
    //     SQLSerialNumber: "f_party_fees_total",
    //     Condition: window.btoa(unescape(encodeURIComponent("%%"))),
    //   },
    //   success: (data) => {
    //     this.total = data;
    //   },
    //   complete: (XMLHttpRequest) => {
    //     requestPretreatment(XMLHttpRequest);
    //   },
    //   dataType: "json",
    // });
    // $.ajax({
    //   headers: requestHeaders(),
    //   url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
    //   type: "GET",
    //   data: {
    //     TableName: "party_organization",
    //     NodeCode: "",
    //   },
    //   success: (data) => {
    //     this.Manager = data; // 直接使用 this
    //   },
    //   complete: (XMLHttpRequest) => {
    //     requestPretreatment(XMLHttpRequest);
    //   },
    //   dataType: "json",
    // });
    this.Treedata();
    this.tongj(a);
  },
  computed: {
    // 计算属性，返回选中的字段
    isAllChecked() {
      return this.checkedFields.length === this.fields.length;
    },
    isfree() {
      return function (row) {
        let obj = this.total.filter(
          (i) =>
            i.Party_Organization_SerialNumber ==
            row.Party_Organization_SerialNumber
        )[0];
        if (obj && obj.total1 > obj.total2) {
          return true;
        }
        return false;
      };
    },
    Colors(){
      return function (i) {
        console.log(i);
        console.log((this.partyMemberMonthlyData[i-1]?.Pay_Quantity || 0 ) ? '#dfe9f8':'#ffffff');
        return (this.partyMemberMonthlyData[i-1]?.Pay_Quantity || 0 ) ? '#dfe9f8':'#ffffff'
      }
    }
  },
  methods: {
    getMonthData(month) {
      // 在z数组中查找匹配的月份数据
      const monthData = this.z.find((item) => item.month === month);

      // 返回找到的数据或默认值
      return monthData || { opened: 0, total: 0 };
    },
    tongj(arg_user) {
      console.log(this.value2);
      let year = this.value2.match(/^\d{4}/)[0]; // 提取前4位数字
      console.log(year); // 输出：2025
      console.log(arg_user);
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        // url: `${mh}/partyOrgChange/queryPayFeesByPartyMember_SerialNumber`,
        url: `${mh}/partyOrgChange/queryPayFeesByPartyOrg_SerialNumber`,
        // url: `http://10.1.0.59:8084/partyOrgChange/queryPayFeesByPartyOrg_SerialNumber`,
        method: "get",
        data: {
          User_Number: arg_user,
          Year: year,
        },
        success: (data) => {
          console.log("返回数据:", data);

          // ===================== 处理 Party_Member 数据 =====================
          // 1. 初始化党员12个月的空数据
          const partyMemberMonthlyData = new Array(12)
            .fill()
            .map((_, index) => ({
              month: index + 1,
              Total_Quantity: 0,
              Pay_Quantity: 0,
            }));

          // 2. 从data.Party_Member中填充党员数据到对应月份
          if (data && Array.isArray(data.Party_Member)) {
            data.Party_Member.forEach((item) => {
              const month = Number(item.Month || item.month); // 兼容大小写
              if (month >= 1 && month <= 12) {
                const index = month - 1;
                partyMemberMonthlyData[index].Total_Quantity =
                  Number(item.Total_Quantity) || 0;
                partyMemberMonthlyData[index].Pay_Quantity =
                  Number(item.Pay_Quantity) || 0;
              }
            });
          }

          console.log("党员按月数据:", partyMemberMonthlyData);

          // ===================== 处理 Party_Org 数据 =====================
          // 1. 初始化党组织12个月的空数据
          const partyOrgMonthlyData = new Array(12).fill().map((_, index) => ({
            month: index + 1,
            payStatus: "0", // 新增状态字段，默认未缴纳
          }));

          // 2. 从data.Party_Org中填充党组织数据到对应月份
          if (data && Array.isArray(data.Party_Org)) {
            data.Party_Org.forEach((item) => {
              const month = Number(item.Month || item.month); // 兼容大小写
              const quantity = Number(item.Quantity) || 0; // 获取缴纳状态

              if (month >= 1 && month <= 12) {
                const index = month - 1;
                // 根据Quantity设置缴纳状态文本
                partyOrgMonthlyData[index].payStatus =
                  quantity === 1 ? "已缴纳" : "未缴纳";
              }
            });
          }

          console.log("党组织按月数据:", partyOrgMonthlyData);

          // ===================== 更新视图数据 =====================
          _this.statistics.partyCongress = {
            partyMembers: partyMemberMonthlyData, // 党员数据
            partyOrgs: partyOrgMonthlyData, // 党组织数据
          };

          // 分别存储两种数据到实例属性
          _this.partyMemberMonthlyData = partyMemberMonthlyData;
          _this.partyOrgMonthlyData = partyOrgMonthlyData;

          console.log("党员按月数据已更新:", _this.partyMemberMonthlyData);
          console.log("党组织按月数据已更新:", _this.partyOrgMonthlyData);
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    changeMonth() {
      let a = getCookie("user"); // 获取cookie
      this.tongj(a);
      this.multipleSelection = [];
    },
    handleCardClick(i) {
      // const szText = event.currentTarget.querySelector(".sz").textContent.trim();
      // if (szText != '全部开展情况') {
      //   this.szText = szText;
      // } else {
      //   this.szText = ''
      // }
      if (this.month == i) {
        this.month = "";
      } else {
        this.month = i;
      }
      this.page.Condition = window.btoa(
        unescape(
          encodeURIComponent(
            "%%,%" +
            this.input +
            "%,%" +
            this.istype +
            "%,%" +
            this.month +
            "%," +
            this.year
          )
        )
      );
      this.postgetList(this.page); // 调用查询方法
    },
    selectable(row) {
      return row.Party_Fee_SerialNumber == "";
    },
    handleAdd1(data) {
      window.location.href =
        "./add2.html?action=Add&nodeKey=" +
        data.Party_Organization_SerialNumber;
    },
    //树的数据
    Treedata() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: mh + "/generalBusiness/getPartyOrganizationTree",
        method: "get",
        success: function (data) {
          console.log(data);
          _this.treeData = data;
          // 使用深拷贝赋值 originalTreeData
          _this.originalTreeData = JSON.parse(JSON.stringify(data));
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    //查询按钮
    check() {
      if (this.value2 == null) {
        this.value2 == "";
      }
      this.page.Condition = window.btoa(
        unescape(
          encodeURIComponent(
            this.value2 + "," + this.value2 + ",%%,%" + this.input + "%"
          )
        )
      );
      //交纳状态
      if (this.value == "0") {
        this.page.ExtensionCondition1 = `AND IFNULL(party_fees.Party_Fee_SerialNumber,'') = ''`;
        this.page.ExtensionCondition = window.btoa(
          unescape(encodeURIComponent(this.page.ExtensionCondition1))
        );
      } else if (this.value == "1") {
        this.page.ExtensionCondition1 = `AND IFNULL(party_fees.Party_Fee_SerialNumber,'') <> ''`;
        this.page.ExtensionCondition = window.btoa(
          unescape(encodeURIComponent(this.page.ExtensionCondition1))
        );
      } else {
        this.page.ExtensionCondition = "";
      }
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
      this.postgetList(this.page);
    },
    //重置按钮
    reset() {
      // 这里可以根据你的实际需求修改逻辑
      window.location.reload();
      console.log("重置操作");
    },
    handleAdds(data) {
      window.location.href =
        "./add1.html?action=Add&nodeKey=" +
        data.Party_Organization_SerialNumber;
    },
    //过滤树的数据
    filterTreeData(data, searchText) {
      return data.filter((item) => {
        if (item.label.includes(searchText)) {
          return true;
        }
        if (item.children) {
          const filteredChildren = this.filterTreeData(
            item.children,
            searchText
          );
          if (filteredChildren.length > 0) {
            item.children = filteredChildren;
            return true;
          }
        }
        return false;
      });
    },
    personalAdd() {
      if (this.multipleSelection.length > 0) {
        this.showDialog2 = true;
      } else {
        this.$message({
          type: "warning",
          message: "请选择要缴费的党员",
        });
      }
      // window.location.href = "./party_feesAdd.html?action=Add";
    },
    Fee_Date_Validity(rule, value, callback) {
      if (!value) {
        callback(new Error("请选择缴费日期"));
      } else if (
        value.split("-")[0] + "-" + value.split("-")[1] !=
        this.value2
      ) {
        callback(new Error("请选择" + this.value2 + "内日期"));
      } else {
        callback();
      }
    },
    handleSubmit() {
      if (this.Fee_Date) {
        console.log(this.multipleSelection);
        let arr = [];
        this.multipleSelection.forEach((item) => {
          arr.push({
            Fee_Date: this.Fee_Date,
            Party_Organization_SerialNumber:
              item.Party_Organization_SerialNumber,
            Party_Member_SerialNumber: item.Party_Member_SerialNumber,
          });
        });
        let lJSONObject_DataSet = {
          Add: { party_fees: arr },
        };
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        if (!lJSONObject_DataSet['Add']) {
          lJSONObject_DataSet['Add'] = new Object();
        }
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface: "generalSave",
          Operation_IP: getIpAddress()
        }]
        submitSave(lJSONObject_DataSet, () => {
          if (res.Status == "success") {
            this.postgetList(this.page);
            this.multipleSelection = [];
            this.showDialog2 = false;
          } else {
            this.$message({
              type: "error",
              message: "操作失败",
            });
          }
          this.loading = false;
        })
        // $.ajax({
        //   headers: requestHeaders("JSON"),
        //   url: `${mh}/generalBusiness/generalSaveByRequestBody`,
        //   method: "post",
        //   data: JSON.stringify({
        //     Data: lJSONObject_DataSet,
        //   }),
        //   success: (res) => {
        //     if (res.Status == "success") {
        //       this.postgetList(this.page);
        //       this.multipleSelection = [];
        //       this.showDialog2 = false;
        //     } else {
        //       this.$message({
        //         type: "error",
        //         message: "操作失败",
        //       });
        //     }
        //   },
        //   complete: (XMLHttpRequest) => {
        //     requestPretreatment(XMLHttpRequest);
        //     this.loading = false;
        //   },
        // });
      } else {
        this.$message({
          type: "warning",
          message: "请选择要缴费时间",
        });
      }
    },
    //编辑按钮
    handleEdit(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./party_feesAdd.html?action=Modify&nodeKey=" + row[primary_key];
    },
    // 弹窗全选
    handleAllChecked(val) {
      console.log(val);
      console.log(val);
      let a; // 提前声明变量 a
      if (val === false) {
        console.log(this.fields);
        a = this.fields.filter((item) => {
          return item.COLUMN_KEY == "PRI";
        });
        console.log(a);
      } else {
        a = [...this.fields]; // 当 val 为 true 时，给 a 赋值为 props.fields 的副本
      }
      // 使用 emit 更新 checkedFields
      this.checkedFields = a;
    },
    saveFields() {
      const selectedFields = this.fields.filter((item) => {
        return this.checkedFields.some(
          (cItem) => cItem && cItem.COLUMN_NAME === item.COLUMN_NAME
        );
      });
      console.log("选中的字段:", selectedFields);
      // 更新 columns
      this.columns = selectedFields;
      this.showDialog = false;
    },
    //树的点击事件
    handleNodeClick(data) {
      console.log(data);
      let arr = [];
      this.Organization(data.children, arr);
      let str = "";
      [data.Party_Organization_SerialNumber, ...arr].forEach((item) => {
        if (str) {
          str += "\r\nOR A.Party_Organization_SerialNumber='" + item + "'";
        } else {
          str = "\r\nA.Party_Organization_SerialNumber='" + item + "'";
        }
      });

      if (str) {
        str = "AND (" + str + ")";
      }
      this.page.ExtensionCondition = window.btoa(
        unescape(encodeURIComponent(this.page.ExtensionCondition1 + str))
      );
      // this.page.Condition = window.btoa(unescape(encodeURIComponent(this.value2+","+this.value2+",%"+data.Party_Organization_SerialNumber+"%,%"+this.input+"%")));
      this.postgetList(this.page);
    },
    Organization(data, arr) {
      data.forEach((item) => {
        arr.push(item.Party_Organization_SerialNumber);
        if (item.children && item.children.length > 0) {
          this.Organization(item.children, arr);
        }
      });
    },
    //显示字段弹窗
    handleOpenDialog() {
      this.showDialog = true;
    },
  },
};
const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;

app.component("yl-monthly-calendar", ylMonthlyCalendar);
app.component("yl-cascader", ylCascader);
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
